﻿using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using DG.Tweening;

public class rocket : MonoBehaviour
{
    public UIFly uiFly;
    public UIGameOver uiGameOver;

    [System.NonSerialized]
    public float goldTemp, power1, power2, power3, upred, hp;
    [System.NonSerialized]
    public float acceleration, accelerationUp, maxup, currentMaxup, maxdown, maxleftright, updown, leftright, speed;
    [System.NonSerialized]
    public bool startGame, island, losePower, hasFenli, iscolding, timeCount;
    //[System.NonSerialized]
    public Vector3 vspeed = Vector3.zero;

    [System.NonSerialized]
    public GameObject rocket1, rocket2, huoyan1, huoyan2, huoyan3, huoyan;

    private Vector3 initpos;
    private Quaternion initRot;

    public Slider sliderHP;
    public GameObject posun1, posun2;
    public GameObject effGet, outCitie;
    public GameObject recordLine;

    private void Awake()
    {
        initpos = transform.position;
        initRot = transform.rotation;
        rocket1 = transform.GetChild(1).gameObject;
        huoyan1 = rocket1.transform.GetChild(0).Find("Rocket_Fire").gameObject;
        rocket2 = transform.GetChild(0).gameObject;
        huoyan2 = rocket2.transform.GetChild(0).GetChild(1).Find("Rocket_Fire").gameObject;
        if (rocket2.transform.GetChild(0).Find("Rocket_Fire1") != null)
            huoyan3 = rocket2.transform.GetChild(0).Find("Rocket_Fire1").gameObject;
        else
            huoyan3 = null;
        huoyan = huoyan1;
    }

    void Start()
    {
        Restart();
        MessageCenter.instance.AddEvtListener(MsgType.citie, GetCitie);
        MessageCenter.instance.AddEvtListener(MsgType.noCitie, LoseCitie);
    }

    public void Restart()
    {
        StopAllCoroutines();

        hight = 0;
        goldTemp = 0;
        updown = 0;
        leftright = 0;
        upred = 0;
        transform.position = initpos;
        transform.rotation = initRot;

        for (int i = 0; i < GameController.instance.toClear.Count; i++)
            Destroy(GameController.instance.toClear[i]);
        GameController.instance.toClear.Clear();
        GameController.instance.currentLv = 0;
        GameController.instance.isCitie = false;

        huoyan.SetActive(false);
        huoyan = huoyan1;
        rocket1.transform.SetParent(this.transform);
        rocket1.transform.localPosition = new Vector3(0, 1.2f, 0);
        rocket1.transform.localRotation = Quaternion.Euler(Vector3.zero);
        rocket1.GetComponent<Rigidbody>().isKinematic = true;
        rocket1.layer = 8;
        timeCount = false;
        time = 0;

        vDir = new Vector3(0, 11, 0);
        vLength = 10;
        maxSpeed = 11;
        vspeed = Vector3.zero;

        posun1.transform.Find("b").gameObject.SetActive(true);
        posun2.transform.Find("b").gameObject.SetActive(true);
        outCitie.SetActive(false);
        posun1.SetActive(false);
        posun2.SetActive(false);
        sliderHP.value = 1;
        sliderHP.gameObject.SetActive(false);
        landCD.gameObject.SetActive(false);
    }

    public void StartGame()
    {
        power1 = DataController.Instance.maxPower1;
        power2 = DataController.Instance.maxPower2;
        power3 = DataController.Instance.maxPower3;
        hp = DataController.Instance.maxHP;
        acceleration = DataController.Instance.sensitive / 9000.0f;
        maxup = DataController.Instance.maxSpeed / 50.0f;
        maxdown = -DataController.Instance.maxSpeed / 10.0f;
        maxleftright = DataController.Instance.maxSpeed / 35.0f;
        recordLine.transform.position = new Vector3(0, PlayerPrefs.GetInt("maxhight"), 0);
        time = 0;
        timeCount = true;
        StartCoroutine(IETimeCount());
        huoyan.SetActive(true);
        Camera.main.DOShakePosition(3, Vector3.one * 0.5f, vibrato: 1000);
        Sequence sequence = DOTween.Sequence();
        sequence.AppendInterval(0.5f)
            .AppendCallback(() =>
            {
                startGame = true;
                island = false;
                landing = false;
                losePower = false;
                hasFenli = false;
                huoyan.SetActive(true);
                sliderHP.gameObject.SetActive(true);
            });
    }

    public void ResetRocket1and2()
    {
        rocket1 = transform.GetChild(1).gameObject;
        huoyan1 = rocket1.transform.GetChild(0).Find("Rocket_Fire").gameObject;
        rocket2 = transform.GetChild(0).gameObject;
        huoyan2 = rocket2.transform.GetChild(0).GetChild(1).Find("Rocket_Fire").gameObject;
        if (rocket2.transform.GetChild(0).Find("Rocket_Fire1") != null)
            huoyan3 = rocket2.transform.GetChild(0).Find("Rocket_Fire1").gameObject;
        else
            huoyan3 = null;
        huoyan = huoyan1;
    }

    int time;
    IEnumerator IETimeCount()
    {
        while (timeCount)
        {
            yield return new WaitForSeconds(1);
            time++;
            uiFly.time.text = time.ToString();
        }
    }

    int upLv = 0;
    [System.NonSerialized]
    public bool up, down, left, right;
    Vector3 vDir = new Vector3(0, 10.5f, 0);
    float vLength = 10;
    float maxSpeed = 10.5f;
    //Update is called once per frame
    void Update()
    {
        if (startGame && !island)
        {
            //改变向量方向
            if (Input.GetKey(KeyCode.D) || right)
                vDir = Quaternion.AngleAxis(0.4f, Vector3.forward) * vDir;
            if (Input.GetKey(KeyCode.A) || left)
                vDir = Quaternion.AngleAxis(0.4f, -Vector3.forward) * vDir;
            if (Input.GetKey(KeyCode.S) || down || losePower)
            {
                //向量长度置为0
                if (vLength > 0)
                    vLength -= 0.5f;
                else
                    vLength = 0;

                huoyan.SetActive(false);
                if (upred > 0)
                    upred -= 0.5f;
                if (huoyan3 != null)
                    huoyan3.SetActive(false);
            }
            else if ((Input.GetKey(KeyCode.W) || up) && power3 > 0 && upred < 100 && !iscolding)
            {
                if (power2 > 0)
                {
                    //向量长度15
                    if (vLength < 15)
                        vLength += 0.25f;
                    else
                        vLength = 15;
                    huoyan.SetActive(true);
                    PowerSub();
                    upLv = 3;
                }
                else
                {
                    //向量长度11
                    if (vLength < 11f)
                        vLength += 0.25f;
                    else
                        vLength = 11f;
                    huoyan.SetActive(false);
                    upLv = 1;
                }
                if (huoyan3 != null)
                    huoyan3.SetActive(true);
                else
                    huoyan.SetActive(true);

                upred += 0.5f;
                power3 -= 0.2f;
                uiFly.Slider3.value = power3 / DataController.Instance.maxPower3;
            }
            else if (power2 > 0)
            {
                //向量长度13
                if (vLength < 13f)
                    vLength += 0.25f;
                else
                    vLength = 13f;

                huoyan.SetActive(true);
                if (huoyan3 != null)
                    huoyan3.SetActive(false);
                PowerSub();
                upLv = 2;
                if (upred > 0)
                    upred -= 0.5f;
            }
            else
            {
                //向量长度0
                if (vLength > 0)
                    vLength -= 0.5f;
                else
                    vLength = 0;

                huoyan.SetActive(false);
                if (huoyan3 != null)
                    huoyan3.SetActive(false);
                if (upred > 0)
                    upred -= 0.5f;
            }
            transform.localRotation = Quaternion.AngleAxis(90, -Vector3.forward) * Quaternion.Euler(new Vector3(0, 0, Mathf.Atan2(vDir.y, vDir.x) * Mathf.Rad2Deg));
            Vector3 vTemp = vDir.normalized * vLength * 1.75f + Vector3.down * 10;
            vspeed += vTemp * Time.deltaTime * 2f;

            //控制最大速度
            if (vLength > 0 && vDir.y >= 0)
            {
                if (maxSpeed > vLength)
                    maxSpeed -= 0.25f;
                else if (maxSpeed < vLength)
                    maxSpeed += 0.25f;
                else
                    maxSpeed = vLength;
                if (GameController.instance.camera.GetComponent<follow>().distance.y < 10.5f)
                    GameController.instance.camera.GetComponent<follow>().distance.y += 0.05f;
                else
                    GameController.instance.camera.GetComponent<follow>().distance.y = 10.5f;
            }
            else
            {
                if (maxSpeed < 30)
                    maxSpeed += 0.5f;
                else
                    maxSpeed = 30;

                if (GameController.instance.camera.GetComponent<follow>().distance.y > 0)
                    GameController.instance.camera.GetComponent<follow>().distance.y -= 0.05f;
                else
                    GameController.instance.camera.GetComponent<follow>().distance.y = 0f;
            }
            if (vspeed.magnitude > maxSpeed)
                vspeed = vspeed.normalized * maxSpeed;

            //transform.Translate(vspeed * Time.deltaTime, Space.World);
            GetComponent<CharacterController>().Move(vspeed * Time.deltaTime);
            speed = vspeed.magnitude;
        }
        SetSlider3Color();


        //判断降落
        if (transform.position.y < 0.5f && vLength <= 0.5f)
            Land();
        else
            NotLand();

        recordLine.transform.position = new Vector3(transform.position.x, recordLine.transform.position.y, recordLine.transform.position.z);
    }

    // Update is called once per frame
    //void Update()
    //{
    //    if (startGame && !island)
    //    {
    //        upLv = 0;
    //        speed = vspeed.magnitude;
    //        if (Input.GetKey(KeyCode.S) || down || losePower)
    //        {
    //            huoyan.SetActive(false);
    //            if (upred > 0)
    //                upred -= 0.5F;
    //        }
    //        else if ((Input.GetKey(KeyCode.W) || up) && power3 > 0 && upred < 100 && !iscolding)
    //        {
    //            if (power2 > 0)
    //            {
    //                huoyan.SetActive(true);
    //                PowerSub();
    //                upLv = 3;
    //            }
    //            else
    //            {
    //                huoyan.SetActive(false);
    //                upLv = 1;
    //            }
    //            upred += 0.5F;
    //            power3 -= 0.2f;
    //            uiFly.Slider3.value = power3 / DataController.Instance.maxPower3;
    //            //vspeed = (Vector3.up * updown + Vector3.right * leftright);
    //        }
    //        else if (power2 > 0)
    //        {
    //            huoyan.SetActive(true);
    //            PowerSub();
    //            upLv = 2;
    //            if (upred > 0)
    //                upred -= 0.5F;
    //        }
    //        else
    //        {
    //            huoyan.SetActive(false);
    //            if (upred > 0)
    //                upred -= 0.5F;
    //        }

    //        if (upLv > 0)
    //        {
    //            currentMaxup = maxup * (upLv * 0.4f + 0.4f);
    //            accelerationUp = acceleration * (upLv * 0.4f + 0.4f);
    //            if (updown < currentMaxup)
    //                updown += accelerationUp;
    //            else
    //                updown -= acceleration;

    //            if (Input.GetKey(KeyCode.D) || right)
    //            {
    //                if (leftright < -maxleftright)
    //                    leftright = -maxleftright;
    //                else
    //                    leftright -= acceleration * 1.5f;
    //            }
    //            if (Input.GetKey(KeyCode.A) || left)
    //            {
    //                if (leftright > maxleftright)
    //                    leftright = maxleftright;
    //                else
    //                    leftright += acceleration * 1.5f;
    //            }
    //        }
    //        else
    //        {
    //            if (updown < maxdown)
    //                updown = maxdown;
    //            else
    //                updown -= acceleration * 3;
    //        }
    //        vspeed = (Vector3.up * updown + Vector3.right * leftright);
    //        transform.localRotation = Quaternion.Euler(new Vector3(0, 0, Mathf.Atan2(-vspeed.x, (vspeed.y - maxdown + 5f) / 2f) * Mathf.Rad2Deg));
    //        transform.Translate(vspeed * Time.deltaTime, Space.World);
    //    }
    //    SetSlider3Color();
    //}

    bool penhuo = true;
    private void PowerSub()
    {
        if (power1 > 0)
            power1 -= 0.2f;
        else if (power2 > 0)
            power2 -= 0.3f;
        if (power1 <= 0 && hasFenli == false)
        {
            Sequence q = DOTween.Sequence();
            huoyan.GetComponent<ParticleSystem>().Stop();
            posun1.transform.Find("b").gameObject.SetActive(false);
            posun2.transform.Find("b").gameObject.SetActive(false);
            updown = -1;
            q.Append(GameController.instance.camera.transform.DOMoveZ(80, 1f))
                .Append(GameController.instance.camera.transform.DOMoveZ(60f, 1f));
            Sequence q2 = DOTween.Sequence();
            q2.AppendInterval(1f)
            .OnComplete(() =>
                {
                    rocket1.GetComponent<Rigidbody>().mass = 10;
                    rocket1.GetComponent<Rigidbody>().drag = 0;
                    huoyan = huoyan2;
                    huoyan.SetActive(true);
                });
            hasFenli = true;
            rocket1.transform.SetParent(null);
            rocket1.GetComponent<Rigidbody>().isKinematic = false;
            rocket1.layer = 0;
        }
        uiFly.Slider1.value = (float)power1 / DataController.Instance.maxPower1;
        uiFly.Slider2.value = (float)power2 / DataController.Instance.maxPower2;
    }

    void SetSlider3Color()
    {
        if (upred > 99)
            iscolding = true;
        if (upred < 1)
            iscolding = false;
        float r, g;
        if (upred < 50)
        {
            r = upred / 50.0f;
            g = 1;
        }
        else
        {
            r = 1;
            g = 1 - (upred - 50) / 50.0f;
        }
        uiFly.Slider3.transform.Find("Background/Fill Area/Fill").GetComponent<Image>().color = new Color(r, g, 0);
    }

    int hight = 0;
    int histroyMaxhight = 0;
    int currentLvMax = 0;

    private void FixedUpdate()
    {
        hight = (int)transform.position.y;
        uiFly.hight.text = hight.ToString() + "M";
        uiFly.SliderHight.value = hight / 1500.0f;
        if (hight > currentLvMax)
        {
            currentLvMax = hight;
            if (currentLvMax > histroyMaxhight)
                histroyMaxhight = currentLvMax;
        }
    }

    Coroutine spup;
    public void SpeedUp()
    {
        if (spup != null)
            StopCoroutine(spup);
        spup = StartCoroutine(IESpeedBack());
    }

    IEnumerator IESpeedBack()
    {
        if (vspeed.y > 0)
        {
            maxSpeed *= 2;
            vspeed *= 2;
            yield return new WaitForSeconds(2);
        }
    }

    public void HIT()
    {
        //updown = -updown / 5;
        //if (leftright > 0)
        //    leftright = maxleftright / 5;
        //else
        //    leftright = -maxleftright / 5;
        posun2.SetActive(true);
        hp -= 700 / 25 * speed;
        if (hp < DataController.Instance.maxHP / 2)
            posun1.SetActive(true);
        sliderHP.value = hp / DataController.Instance.maxHP;
        if (hp <= 0)
        {
            Handheld.Vibrate();
            ShowGameOver();
        }
    }

    public void LosePower()
    {
        StartCoroutine(IELosePower());
    }

    IEnumerator IELosePower()
    {
        losePower = true;
        yield return new WaitForSeconds(2);
        losePower = false;
    }

    public void PowerPlus()
    {
        effGet.GetComponent<ParticleSystem>().Play();
        if(posun1) power1 = DataController.Instance.maxPower1;
        power1 += 50;
    }

    public void MoneyPlus()
    {
        effGet.GetComponent<ParticleSystem>().Play();
        goldTemp += 25;
        uiFly.money.text = goldTemp.ToString();
    }

    public bool landing = false;
    public void Land()
    {

        if (landing == false)
        {
            if (speed > 20)
                hp -= 600 + (speed - 20) * 50;
            else
                hp -= 200;

            if (hp <= 0)
                ShowGameOver();
            else
                pp = StartCoroutine(LandCountDown());
            landing = true;
        }
    }

    Coroutine pp;
    public void NotLand()
    {
        if (landing)
        {
            landCD.gameObject.SetActive(false);
            if (pp != null)
                StopCoroutine(pp);
            landing = false;
        }
    }

    public Text landCD;
    IEnumerator LandCountDown()
    {
        landCD.gameObject.SetActive(true);
        landCD.text = 1.ToString();
        yield return new WaitForSeconds(1);
        landCD.text = 2.ToString();
        yield return new WaitForSeconds(1);
        landCD.text = 3.ToString();
        yield return new WaitForSeconds(1);
        landCD.text = "成功降落";
        yield return new WaitForSeconds(0.1f);
        island = true;
        startGame = false;
        landCD.gameObject.SetActive(false);
        ShowGameOver();
    }

    public void ShowGameOver()
    {
        if (startGame)
        {
            if (hp <= 0)
                startGame = false;
        }
        if (!startGame || island)
        {
            if (hp <= 0)
            {
                Sequence se = DOTween.Sequence();
                se.AppendCallback(() =>
                {
                    GameObject bao = Instantiate(Resources.Load("Boom") as GameObject, transform.position + new Vector3(0, 1, 2), Quaternion.identity);
                    GameController.instance.toClear.Add(bao);
                }).AppendInterval(0.5f)
                    .AppendCallback(() =>
                    {
                        uiGameOver.gameObject.SetActive(true);
                        uiGameOver.GetComponent<UIGameOver>().SetText(currentLvMax, time, (int)goldTemp, hp / DataController.Instance.maxHP, hp > 0);
                        PlayerPrefs.SetInt("maxhight", histroyMaxhight);
                    });
            }
            else
            {
                uiGameOver.gameObject.SetActive(true);
                uiGameOver.GetComponent<UIGameOver>().SetText(currentLvMax, time, (int)goldTemp, hp / DataController.Instance.maxHP, hp > 0);
                PlayerPrefs.SetInt("maxhight", histroyMaxhight);
            }
        }
    }

    void GetCitie(CustomMessage cm)
    {
        outCitie.SetActive(true);
    }
    void LoseCitie(CustomMessage cm)
    {
        outCitie.SetActive(false);
    }
    private void OnDestroy()
    {
        MessageCenter.instance.RemoveEvtListener(MsgType.citie, GetCitie);
        MessageCenter.instance.RemoveEvtListener(MsgType.noCitie, LoseCitie);
    }
}